package com.example.filter;

import com.example.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取到请求路径
        String requestURI = request.getRequestURI(); // /api/emp/login
        //2.判断请求路径是否包含login，如果包含，说明是登录操作，放行
        if (requestURI.contains("login")) {
            log.info("登录操作，放行...");
            filterChain.doFilter(request, response);
            return;
        }
        //3.获取请求头中的令牌（token）
        String token = request.getHeader("token");
        //4.判断令牌是否存在，如果不存在，返回错误结果（响应401状态码）
        if (token == null || token.isEmpty()) {
            log.info("令牌为空，响应401状态码...");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //5.如果存在，解析token，如果解析失败，返回错误结果（响应401状态码）
        try {
            //解析token
            log.info("解析令牌：{}", token);
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("令牌解析失败，响应401状态码...");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //6.放行
        log.info("令牌合法，放行...");
        filterChain.doFilter(request, response);
    }
}
